<template>
  <div class="user-container">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-button type="success" @click="showAddUser">添加用户</el-button>
      <!-- 添加用户对话框 -->
      <el-dialog title="添加用户" :visible.sync="addUserDialog.dialogVisible" width="30%">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="ruleForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="ruleForm.password" type="password"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model="ruleForm.phone" type="number"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addUserDialog.dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUserSubmit">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 用户表格 -->
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="user_name" label="用户名" width="200">
        </el-table-column>
        <el-table-column prop="user_phone" label="电话" width="">
        </el-table-column>
        <el-table-column prop="role.role_name" label="角色" width="200">
        </el-table-column>
        <el-table-column label="状态" width="200">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.user_status" active-color="#13ce66" inactive-color="#ff4949" @change="switchChange(scope.row.user_status,scope.row.id)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="400">
          <template slot-scope="scope">
            <el-button @click="editDialog(scope.row)" type="primary" icon="el-icon-edit"></el-button>
            <el-button type="danger" icon="el-icon-delete" @click="delUser(scope.row)"></el-button>
            <el-button type="warning" icon="el-icon-setting" @click="changeRole(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 编辑用户对话框 -->
      <el-dialog title="编辑用户" :visible.sync="editUserDialog.dialogVisible" width="30%">
        <el-form :model="newForm" :rules="rules" ref="newForm" label-width="100px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="newForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model="newForm.phone" type="number"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editUserDialog.dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editSubmit">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改角色对话框 -->
      <el-dialog title="修改角色" :visible.sync="editRoleDialog.dialogVisible" width="30%">
        <el-form :model="newRoleForm" :rules="rules" ref="newRoleForm" label-width="100px">
          <el-form-item label="当前用户：">{{newRoleForm.username}}</el-form-item>
          <el-form-item label="当前角色：">{{newRoleForm.currentRole}}</el-form-item>
          <el-form-item label="新角色" prop="newRole">
            <el-select v-model="newRoleForm.newRole" placeholder="请选择新的角色">
              <el-option label="系统管理员" value='1'></el-option>
              <el-option label="商品管理员" value='2'></el-option>
              <el-option label="客服" value='3'></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editRoleDialog.dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="changeRuleSubmit">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'UserCom',
  methods: {
    showAddUser() {
      this.addUserDialog.dialogVisible = true
    },
    addUserSubmit() {
      // 验证
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          const { data: rel } = await this.$http.post('user', this.ruleForm)
          if (rel.code === 20000) {
            this.$message({
              message: '创建成功',
              type: 'success'
            })
          } else {
            this.$message.error('服务器错误')
          }
          this.$refs.ruleForm.resetFields()
          this.addUserDialog.dialogVisible = false
          this.userDataInit()
        } else {
          this.$message.error('创建失败')
          return false
        }
      })
    },
    // 账号状态修改
    async switchChange(value, id) {
      console.log(value, id)
      const { data: rel } = await this.$http.put(`user/${id}`, { newStatus: value })
      if (rel.code === 20000) {
        this.$message({
          type: 'success',
          message: '已修改账号状态'
        })
      } else {
        this.$message.error('异常')
      }
    },
    // 删除用户
    delUser(row) {
      console.log(row.id)
      this.$confirm('此操作将永久删除该账号, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: rel } = await this.$http.delete(`user/${row.id}`)
          if (rel.code === 20000) {
            this.$message({
              type: 'success',
              message: '删除账号成功!'
            })
          } else {
            this.$message.error('服务器错误')
          }
          this.userDataInit()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 获取当前用户的信息
    async getCurrentUser(id) {
      const { data: rel } = await this.$http.get(`user/${id}`)
      this.newForm.username = rel.data.user_name
      this.newRoleForm.username = rel.data.user_name
      this.newRoleForm.currentRole = rel.data.role.role_name
    },
    // 编辑弹窗
    async editDialog(row) {
      this.editId = row.id
      this.getCurrentUser(row.id)
      this.editUserDialog.dialogVisible = true
    },
    // 编辑提交
    editSubmit() {
      this.$refs.newForm.validate(async valid => {
        if (valid) {
          const { data: rel } = await this.$http.put(`user/${this.editId}`, { newPhone: this.newForm.phone })
          if (rel.code === 20000) {
            this.$message({
              message: '编辑成功',
              type: 'success'
            })
          } else {
            this.$message.error('异常')
          }
          this.editUserDialog.dialogVisible = false
          this.userDataInit()
        } else {
          this.$message.error('修改失败')
          return false
        }
      })
    },
    // 数据显示
    async userDataInit() {
      const role = localStorage.getItem('userrole')
      if (role !== '1') {
        this.$message.error('权限错误')
        return false
      }
      const { data: rel } = await this.$http.get('user')
      if (rel.code === 20000) {
        this.tableData = rel.data
      }
    },
    // 修改角色弹窗
    changeRole(row) {
      this.editId = row.id
      this.getCurrentUser(row.id)
      this.editRoleDialog.dialogVisible = true
      this.newRoleForm.newRole = ''
    },
    // 修改角色提交
    changeRuleSubmit() {
      const value = parseInt(this.newRoleForm.newRole)
      console.log(value)
      this.$refs.newRoleForm.validate(async valid => {
        if (valid) {
          const { data: rel } = await this.$http.put(`user/${this.editId}`, { newRole: value })
          if (rel.code === 20000) {
            this.$message({
              message: '修改角色成功',
              type: 'success'
            })
          } else {
            this.$message.error('异常')
          }
          this.editRoleDialog.dialogVisible = false
          this.userDataInit()
        } else {
          this.$message.error('修改失败')
          return false
        }
      })
    }
  },
  data() {
    return {
      editId: 0,
      tableData: [],
      addUserDialog: {
        dialogVisible: false
      },
      editUserDialog: {
        dialogVisible: false
      },
      editRoleDialog: {
        dialogVisible: false
      },
      // 添加用户表单数据
      ruleForm: {
        username: '',
        password: '',
        phone: ''
      },
      rules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入电话号码', trigger: 'blur' }],
        newRole: [{ required: true, message: '请选择角色', trigger: 'blur' }]
      },
      // 编辑用户表单
      newForm: {
        username: '',
        phone: ''
      },
      // 修改角色表单
      newRoleForm: {
        username: '',
        currentRole: '',
        newRole: ''
      }
    }
  },
  created() {
    this.userDataInit()
  }
}
</script>

<style scoped>
.box-card {
  margin-top: 20px;
}
.el-table {
  margin-top: 20px;
}
</style>
